package com.sk.waste.app.utils

import android.content.Context
import android.os.Environment
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Scanner


/**
 *  @time 2024/7/12  8:44
 *  @author Im_jingwei
 *  @desc 日志记录
 */
@Suppress("UNREACHABLE_CODE")
object LogUtil {

    private var arrayLog: JSONArray? = null
    private val LOG_DIR: String = Environment.getExternalStorageDirectory().absolutePath + "/lcxfglapp/"

    /**
     *  @time 2024/8/30  9:34
     *  @author Im_jingwei
     *  @desc 创建bufferedWriter
     */
    fun init() {
        createLogDirs()
    }

    /**
     *  @time 2024/9/23  10:16
     *  @author Im_jingwei
     *  @desc 创建文件夹
     */
    private fun createLogDirs() {
        val tempFile = File(LOG_DIR)
        if (!tempFile.exists()) {
            tempFile.mkdirs()
        }
    }

    /************************************  原方案json整体写入 废弃 ***************************************/

    /**
     *  @time 2024/8/22  15:42
     *  @author Im_jingwei
     *  @desc 保存到本地
     */
    fun saveLogToDir() {
        val time = SimpleDateFormat("yyyy_MM_dd HH:mm:ss").format(Date())
        val filePath = LOG_DIR + "track_" + time + ".log"
        val temp = File(filePath)
        if (!temp.exists()) {
            val dirFile = temp.parentFile
            if (!dirFile!!.exists())
                dirFile.mkdirs()
            temp.createNewFile()
        }
        try {
            Log.d("LCLOG_SAVELOG", "开始保存轨迹日志-----------------")
            val fileWriter = FileWriter(filePath)
            val bufferedWriter = BufferedWriter(fileWriter)
            bufferedWriter.write(arrayLog.toString())
            bufferedWriter.close()
            arrayLog = null
            Log.d("LCLOG_SAVELOG", "本次轨迹日志保存成功！")
        } catch (e: IOException) {
            Log.e("LCLOG_SAVELOG", e.message.toString())
            e.printStackTrace()
        }
    }

    /**
     *  @time 2024/11/25  14:47
     *  @author Im_jingwei
     *  @desc 解析asset中的文件
     */
    fun parseJsonFromAsset(context: Context, fileName: String?): JSONArray? {
        val manager = context.assets
        val jsonString = StringBuilder()
        try {
            manager.open(fileName!!).use { `is` ->
                Scanner(`is`, StandardCharsets.UTF_8.name()).use { scanner ->
                    while (scanner.hasNextLine()) {
                        jsonString.append(scanner.nextLine())
                    }
                    return JSONArray(jsonString.toString())
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }
    }

}